package fr.emse.tsc;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class WenAccess extends Activity {
	static final int DIALOG_DISCONNECT = 0;
	static final int DIALOG_ERROR = 1;

	private String adresseIP = null;
	private int port = 0;
	private String wname = null;
	private Socket socket = null;
	private String errorMessage = null;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tsc_wen);
        adresseIP = Config.getWServer(this);
        port = Integer.parseInt(Config.getWPort(this));
        wname = Config.getWName(this);
        Log.i("LENACCESS", "On Create: " + adresseIP);
    	connect();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to disconnect?")
		       .setCancelable(false)
		       .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                disconnect();
		           }
		       })
		       .setNegativeButton("Quit", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();       
		return alert;
	}
	
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case DIALOG_DISCONNECT:
            	break;
            case DIALOG_ERROR:
                ((AlertDialog) dialog).setMessage(errorMessage);
                break;
        }
    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.mConnect :
        	connect();
            return true;
        case R.id.mDisconnect :
            showDialog(DIALOG_DISCONNECT);
            return true;
        }
        return false;
    }
 
	private void connect() {
        try {
            adresseIP = Config.getWServer(this);
            port = Integer.parseInt(Config.getWPort(this));
            wname = Config.getWName(this);
        	Toast toast = Toast.makeText(WenAccess.this, "Connect " + wname + " to " + adresseIP, Toast.LENGTH_SHORT);
        	toast.setGravity(Gravity.CENTER, 0, 0);
        	toast.show();
        	InetAddress serverAddr = InetAddress.getByName(adresseIP);
            socket = new Socket(serverAddr, port);
            String message = "HELO " + wname;
            PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
            out.print(message);
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String reponse = in.readLine();
            if (reponse.equals("OK")) {
            }
            else {
            	errorMessage = reponse;
            	showDialog(DIALOG_ERROR);
            }
        }
        catch (Exception e) {
        	errorMessage = e.getMessage();
        	showDialog(DIALOG_ERROR);
        }
	}
	
	private void disconnect() {
		if (socket != null) {
			try {
	            String message = "QUIT";
	            PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
	            out.print(message);
	            out.flush();
			} catch (IOException e) {
	        	errorMessage = e.getMessage();
	        	showDialog(DIALOG_ERROR);
			}
			try {
				socket.close();
			}
			catch (IOException e) {
	        	errorMessage = e.getMessage();
	        	showDialog(DIALOG_ERROR);				
			}
		}
	}
}
